package cn.muqingfeng.util;

import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.v4.util.LruCache;
import android.text.TextUtils;

import com.android.volley.toolbox.ImageLoader.ImageCache;

public class MemoryCache implements ImageCache {

	/** 默认的内存大小 */
	private static final int DEFAULT_CACHE_SIZE = 5 * 1024 * 1024; // 默认5M大小
	private LruCache<String, Bitmap> mMemoryCache;

	public MemoryCache() {
		this(DEFAULT_CACHE_SIZE);
	}

	public MemoryCache(int maxSize) {
		mMemoryCache = new LruCache<String, Bitmap>(maxSize) {

			@Override
			protected int sizeOf(String key, Bitmap value) {
				return getBitmapSize(value);
			}
		};

	};

	@Override
	public Bitmap getBitmap(String url) {
		return mMemoryCache.get(url);
	}

	@Override
	public void putBitmap(String url, Bitmap bitmap) {
		if (TextUtils.isEmpty(url) || bitmap == null) {
			return;
		}
		mMemoryCache.put(url, bitmap);
	}

	private  static boolean hasHoneycombMR1() {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR1;
    }
	
	@TargetApi(12)
	private int getBitmapSize(Bitmap bitmap) {

		if (hasHoneycombMR1()) {
			return bitmap.getByteCount();
		}
		// Pre HC-MR1
		return bitmap.getRowBytes() * bitmap.getHeight();
	}

	@Override
	public void clearCache() {
		mMemoryCache.evictAll();
	}

	@Override
	public void removeBitmap(String url) {
		mMemoryCache.remove(url);
	}
}
